<template>
  <!-- 环境告警 -->
  <div>
    <!-- 搜索 -->
    <div
      class="search-area"
      v-if="isShowSearch"
      style="border-bottom: 1px dashed #33414c; margin-bottom: 15px"
    >
      <div class="form">
        <el-form
          :model="listQuery"
          ref="listQuery"
          size="small"
          :inline="true"
          label-width="115px"
        >
          <el-form-item :label="$t('告警项') + ':'">
            <el-input
              v-model="listQuery.alarmCategory"
              :placeholder="$t('请输入')"
              clearable
              size="medium"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label-width="128px" :label="$t('检测结果') + ':'">
            <el-input
              v-model="listQuery.alarmValue"
              :placeholder="$t('请输入')"
              clearable
              size="medium"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('开始时间') + ':'">
            <el-date-picker
              v-model="listQuery.startTime"
              type="date"
              size="medium"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              default-time="['00:00:00', '23:59:59']"
              :placeholder="$t('选择开始时间')"
              :picker-options="pickerOptionsStart"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('结束时间') + ':'">
            <el-date-picker
              v-model="listQuery.endTime"
              type="date"
              size="medium"
              :placeholder="$t('选择结束时间')"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              default-time="['00:00:00', '23:59:59']"
              :picker-options="pickerOptionsEnd"
            >
            </el-date-picker>
          </el-form-item>
          <el-collapse-transition>
            <div v-if="isCollapse">
              <el-form-item :label="$t('告警内容') + ':'">
                <el-input
                  v-model="listQuery.alarmContent"
                  :placeholder="$t('请输入')"
                  clearable
                  size="medium"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <!-- <el-form-item label="处理状态:">
                <el-checkbox-group v-model="listQuery.handleStatuss">
                  <el-checkbox label="0">已处理</el-checkbox>
                  <el-checkbox label="1">未处理</el-checkbox>
                </el-checkbox-group>
              </el-form-item> -->
            </div>
          </el-collapse-transition>
        </el-form>
        <img
          @click="collapseBtn"
          :src="collapseUrl"
          class="collapse-img"
          alt=""
        />
      </div>
      <div class="search-area-btn btns">
        <div
          v-hasPermi="['data:alarm:search']"
          @click="serachBtn"
          class="serch-btn cuver-point"
        >
          {{ $t("搜索") }}
        </div>
        <div
          v-hasPermi="['data:alarm:reset']"
          @click="resetFormBtn('listQuery')"
          class="reset-btn cuver-point"
        >
          {{ $t("重置") }}
        </div>
      </div>
    </div>
    <div class="table" :style="{ padding: isShowSearch ? '25px' : '' }">
      <div class="self">
        <el-table
          :data="inspectResultsTable"
          style="width: 100%"
          :height="height"
        >
          <el-table-column
            prop="alarmCategory"
            align="center"
            :label="$t('告警项')"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="alarmValue"
            align="center"
            show-overflow-tooltip
            :label="$t('检测结果')"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="resourceInfo"
            :label="$t('采集信息')"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span
                v-for="(item, index) in scope.row.mediaType"
                :key="index"
                class="column-imgs"
              >
                <img
                  src="../../../../assets/images/objectData/picture.png"
                  alt=""
                  @click="rowClick(scope.row, index, 'showPic')"
                  v-if="item == '1'"
                />
                <img
                  src="../../../../assets/images/objectData/video.png"
                  alt=""
                  @click="rowClick(scope.row, index, 'showVideo')"
                  v-if="item == '3'"
                />
                <img
                  src="../../../../assets/images/objectData/audio.png"
                  alt=""
                  @click="rowClick(scope.row, index, 'showAudio')"
                  v-if="item == '2'"
                />
                <span v-if="item == '0' || item == ''">{{ $t("-") }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="alarmContent"
            :label="$t('告警内容')"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            prop="startTime"
            width="150"
            :label="$t('告警开始时间')"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            prop="endTime"
            width="150"
            :label="$t('告警结束时间')"
            show-overflow-tooltip
          ></el-table-column>
          <!-- <el-table-column align="center" prop="handleStatus" label="审核状态">
        <template slot-scope="scope">
          <div
            :style="{
              color: scope.row.handleStatus == 0 ? 'green' : 'gray',
            }"
          >
            {{ scope.row.handleStatus == 0 ? "已处理" : " 未处理" }}
          </div>
        </template>
      </el-table-column> -->
          <!-- <el-table-column label="操作" width="70" align="center">
        <template slot-scope="scope">
          <div @click="handleClick(scope.row)" class="serch-btn column-btn">
            处理
          </div>
        </template>
      </el-table-column> -->
        </el-table>
      </div>
    </div>
    <div class="pagenation" v-if="isShowSearch">
      <pagination
        :total="total"
        :page.sync="listQuerySubmit.pageNum"
        :limit.sync="listQuerySubmit.pageSize"
        @pagination="getenvAlarminfo"
      >
      </pagination>
    </div>
    <!-- dialog -->
    <el-dialog
      :title="$t('查看')"
      :visible.sync="dialogVisible"
      width="560px"
      @close="closeDialog"
    >
      <!-- 图片 -->
      <div
        v-if="
          dialogBooArr.find((item) => {
            return item.title == 'showPic';
          }).bool
        "
      >
        <div class="dialog-lineone">
          <div>{{ $t("拍摄时间") + "：" }}{{ dialogDetail.createTime }}</div>
          <div>{{ $t("文件名") + "：" }}{{ dialogDetail.resourceName }}</div>
          <div @click="downLoad" class="el-icon-download cursor-pointer"></div>
        </div>
        <div class="img-pa">
          <img ref="togglePic" style="width: 100%" :src="dialogSrc" alt="" />
          <img
            v-if="!isScreenFull"
            @click="togglePic()"
            class="screenFull"
            src="../../../../assets/images/screen.png"
            alt=""
          />
        </div>
      </div>
      <!-- 视频 -->
      <div
        v-if="
          dialogBooArr.find((item) => {
            return item.title == 'showVideo';
          }).bool
        "
      >
        <div class="dialog-lineone">
          <div>{{ $t("录制时间") + "：" }}{{ dialogDetail.createTime }}</div>
          <div>{{ $t("文件名") + "：" }}{{ dialogDetail.resourceName }}</div>
          <div @click="downLoad" class="el-icon-download cursor-pointer"></div>
        </div>
        <div>
          <video controls style="width: 100%" ref="showVideo">
            <source :src="dialogSrc" type="video/mp4" />
          </video>
        </div>
      </div>
      <!-- 音频 -->
      <div
        v-if="
          dialogBooArr.find((item) => {
            return item.title == 'showAudio';
          }).bool
        "
      >
        <div class="dialog-lineone">
          <div>{{ $t("录制时间") + "：" }}{{ dialogDetail.createTime }}</div>
          <div>{{ $t("文件名") + "：" }}{{ dialogDetail.resourceName }}</div>
          <div @click="downLoad" class="el-icon-download cursor-pointer"></div>
        </div>
        <div class="display:flex" v-if="currentAudioUrl.src != ''">
          <aplayer :music="currentAudioUrl" ref="showAudio"></aplayer>
          <div class="change-audio">
            <div class="reset-btn el-icon-arrow-left"></div>
            <div class="reset-btn el-icon-arrow-right"></div>
          </div>
        </div>
      </div>
      <div slot="footer" style="display: flex; justify-content: flex-end">
        <div class="reset-btn" @click="dialogVisible = false">
          {{ $t("取消") }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
/**
 * 环境告警
 */
import aplayer from "vue-aplayer";
import screenfull from "screenfull";
import { API_synthAlarm } from "@/api/robot/monitor.js";
import { API_getResourceinfo } from "@/api/data/inspectrecords.js";
export default {
  name: "",
  components: {
    aplayer,
  },
  props: {
    isShowSearch: {
      type: Boolean,
      default: false,
    },
    height: { type: Number, default: 218 },
  },
  data() {
    return {
      pickerOptionsStart: {
        disabledDate: (time) => {
          let endDateVal = this.listQuery.endTime;
          if (endDateVal) {
            return (
              time.getTime() >=
              new Date(endDateVal).getTime() + 1 * 24 * 60 * 60 * 1000
            );
          }
        },
      },
      // 结束日期
      pickerOptionsEnd: {
        disabledDate: (time) => {
          let beginDateVal = this.listQuery.startTime;
          if (beginDateVal) {
            return time.getTime() < new Date(beginDateVal).getTime();
          }
        },
      },
      isScreenFull: false, //是否全屏
      isCollapse: false, //展开折叠
      sevePort: window.location.protocol + "//" + window.location.host,
      // 查询条件
      listQuery: {
        alarmCategory: null, //告警项
        alarmValue: null, //检测结果
        alarmContent: null,
        handleStatuss: [], //处理状态
        startTime: null,
        endTime: null,
        pageNum: 1,
        pageSize: 10,
      },
      total: 0, // 分页总数
      listQuerySubmit: {}, // 提交参数
      inspectResultsTable: [], // 表格数据
      dialogSrc: "", //弹框URL
      dialogDetail: {}, //弹框图片数据
      currentAudioUrl: {
        src: "",
      }, //音频
      dialogVisible: false, //图片dialog
      //控制弹框展示组件
      dialogBooArr: [
        {
          title: "showPic",
          bool: false,
        },
        {
          title: "showVideo",
          bool: false,
        },
        {
          title: "showAudio",
          bool: false,
        },
      ],
      downLoadUrl: "",
      websock: null,
      tableTimer: null,
    };
  },
  watch: {
    isCollapse: {
      handler(val) {
        if (val == true) {
          this.collapseUrl = require("../../../../assets/less.png");
        } else {
          this.collapseUrl = require("../../../../assets/more.png");
        }
      },
      immediate: true,
      deep: true,
    },
  },
  created() {
    //初始化WebSocket
    this.listQuerySubmit = Object.assign({}, this.listQuery);
    this.getenvAlarminfo();
  },
  mounted() {
    // 监听窗口大小改变，screenfull.isFullscreen的值为是否全屏，若是则true，反之false
    window.onresize = () => {
      this.isScreenFull = screenfull.isFullscreen;
    };
    if (!this.isShowSearch) {
      this.tableTimer = setInterval(() => {
        this.getenvAlarminfo();
      }, 1000);
    }
  },
  methods: {
    /**折叠、展开按钮 */
    collapseBtn() {
      this.isCollapse = !this.isCollapse;
    },
    /** 重置按钮操作 */
    resetFormBtn(formName) {
      this.listQuery = {
        startTime: null,
        endTime: null,
        alarmContent: null,
        handleStatuss: [],
        alarmCategory: null, //告警项
        alarmValue: null, //检测结果
        pageNum: 1,
        pageSize: 10,
      };
      this.serachBtn();
    },
    /**搜索 */
    serachBtn() {
      this.listQuery.pageNum = 1;
      this.listQuerySubmit = Object.assign({}, this.listQuery);
      this.getenvAlarminfo();
    },
    /**全屏方法 */
    togglePic() {
      if (!screenfull.isEnabled) {
        //判断一下浏览器是否支持全屏显示
        this.$message({
          message: this.$t("浏览器不能全屏"),
          type: "warning",
        });
        return false;
      }
      screenfull.toggle(this.$refs.togglePic);
    },
    /**获取环境告警 */
    getenvAlarminfo() {
      let handleStatuss = this.listQuerySubmit.handleStatuss;
      if (handleStatuss && handleStatuss.length > 0) {
        if (handleStatuss.indexOf(",") == -1) {
          handleStatuss = String(handleStatuss);
        } else {
          handleStatuss = handleStatuss.join(",");
        }
      }
      API_synthAlarm({ ...this.listQuerySubmit }).then((res) => {
        if (res.code == 200) {
          this.inspectResultsTable = res.rows;
          this.inspectResultsTable.forEach((item) => {
            let mediaType = item.mediaType || "";
            item.mediaType = mediaType.split(",");
            let mediaId = item.mediaId || "";
            item.mediaId = mediaId.split(",");
          });
          if (this.inspectResultsTable.length > 100)
            this.inspectResultsTable.length = 100;
          this.total = Number(res.total);
          this.listQuery = Object.assign({}, this.listQuerySubmit);
        }
      });
    },
    /**表格点击视频音频事件 */
    rowClick(rowInfo, index, type) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$set(this, "dialogSrc", "");
      let id = rowInfo.mediaId[index];
      //展示图片、视频、音频
      API_getResourceinfo({ id: id })
        .then((res) => {
          if (res.code == 200) {
            if (res.data) {
              switch (type) {
                case "showPic":
                  this.$nextTick(() => {
                    this.$set(
                      this,
                      "dialogSrc",
                      this.sevePort + res.data.resourceUrl
                    );
                  });
                  break;
                case "showVideo":
                  this.$refs.showVideo.src =
                    // "http://192.168.61.11:80" + res.data.resourceUrl;
                    this.sevePort + res.data.resourceUrl;
                  break;
                case "showAudio":
                  this.currentAudioUrl = {
                    // src: "http://192.168.61.11:80" + res.data.resourceUrl,
                    src: this.sevePort + res.data.resourceUrl,
                    title: res.data.resourceName,
                  };
                  break;
              }
              this.dialogDetail = res.data;
              this.downLoadUrl = res.data.resourceUrl;
              this.dialogVisible = true;
            } else {
              this.$message.error(this.$t("暂无数据"));
            }
          } else {
            this.dialogSrc = "";
            this.dialogDetail = {};
            this.$message.error(this.$t("请求失败请重试"));
          }
        })
        .finally(() => {
          loading.close();
        });

      this.dialogBooArr.forEach((item) => {
        if (item.title == type) {
          item.bool = true;
        } else {
          item.bool = false;
        }
      });
    },
    downLoad() {
      this.$download.resource(this.downLoadUrl);
    },
    /**close dialog */
    closeDialog() {
      this.dialogVisible = false;
      this.dialogBooArr.forEach((item) => {
        if (item.title == "showPic") return;
        if (item.bool) {
          this.$refs[item.title].pause();
        }
      });
    },
  },
  beforeDestroy() {
    // clearInterval(this.tableTimer);
    // this.tableTimer = null;
  },
};
</script>

<style scoped lang="scss">
.column-btn {
  display: flex;
  width: 46px;
  height: 28px;
  justify-content: center;
  align-items: center;
  font-size: 14px;
}
.column-imgs {
  img {
    width: 24px;
    height: 24px;
    cursor: pointer;
  }
}
/** 音频播放器*/
.aplayer {
  background-color: transparent;
  color: #fff;
  .aplayer-body {
    display: flex;
    flex-direction: column;
    .aplayer-pic {
    }
  }
}
/**弹框样式 */
.dialog-lineone {
  display: flex;
  margin: 0 0 20px 0;
  div:nth-child(1) {
    width: 50%;
  }
  div:nth-child(2) {
    width: 45%;
  }
  div:nth-child(3) {
    width: 5%;
  }
}
.change-audio {
  display: flex;
  margin-top: 20px;
  justify-content: center;
  div:nth-child(2) {
    margin-left: 20px;
  }
}
.img-pa {
  position: relative;
  .screenFull {
    position: absolute;
    bottom: 10px;
    right: 10px;
    width: 20px;
    height: 20px;
    display: inline-block;
    cursor: pointer;
    z-index: 999;
  }
}

::v-deep {
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 195px;
  }
  .el-dialog:not(.is-fullscreen) {
    margin-top: 30vh !important;
  }
  .el-checkbox {
    margin-right: 10px;
  }
  .el-dialog .el-dialog__body {
    text-align: left;
  }
}
.pagenation {
  position: absolute;
  bottom: 30px;
  right: 20px;
}
</style>
